package services

import (
	"demo/enmu"
	"demo/models"
	"demo/pkg/database"
	"demo/utils"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

// 注册函数
func RegisterPostService(c *gin.Context) {
	user := new(models.Userinfo)
	resp := models.GetDefaultResp()
	if err := c.ShouldBindJSON(&user); err != nil {
		setApiError(c, http.StatusInternalServerError, resp, err)
		return
	}
	if register(user.Username,user.Email,user.Password) {
		c.JSON(http.StatusOK, resp)
	} else {
		resp.Code, resp.Msg = enmu.BAD_REGIRSTER_INFO_CODE, enmu.BAD_REGIRSTER_INFO_MSG 
		c.JSON(http.StatusBadRequest,resp)
	}
}

func register(username,email, password string) bool {
	user := &models.Userinfo{Email: email}
	hashedPassword := utils.HashPassword(password, email)
	user.Password = hashedPassword
	user.Username=username
	err := database.InsertOneUser(user)
	if err != nil {
		logrus.Errorln("insert register user error : ", err)
		return false
	}
	return true
}
